package site.isscloud.project.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.isscloud.project.domain.*;
import site.isscloud.project.mapper.*;
import site.isscloud.project.service.IPjTemperatureStatsService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 温度统计Service业务层处理
 */
@Service
public class PjTemperatureStatsServiceImpl implements IPjTemperatureStatsService {

    private static final Logger log = LoggerFactory.getLogger(PjTemperatureStatsServiceImpl.class);
    private static final Logger statisticLog = LoggerFactory.getLogger("statistic");

    private static final DateTimeFormatter MINUTE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:00");
    private static final DateTimeFormatter HOUR_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00:00");

    @Autowired
    private PjRealtimeTemperatureDataMapper pjRealtimeTemperatureDataMapper;

    @Autowired
    private PjStatsTemperatureMinuteMapper pjStatsTemperatureMinuteMapper;

    @Autowired
    private PjStatsTemperatureHourMapper pjStatsTemperatureHourMapper;

    @Autowired
    private PjStatsTemperatureDailyMapper pjStatsTemperatureDailyMapper;

    // 在 PjTemperatureStatsServiceImpl 类中添加这个方法
    @Override
    public TemperatureTrendResponse getTemperatureTrendData(String deviceNo, Integer channelNo,
                                                            String startTime, String endTime,
                                                            String trendType, Integer startMeter,
                                                            Integer endMeter) {
        // 根据 trendType 调用不同的方法
        if ("hour".equalsIgnoreCase(trendType)) {
            return getMinuteTrendData(deviceNo, channelNo, startTime, endTime, startMeter, endMeter);
        } else if ("day".equalsIgnoreCase(trendType)) {
            return getHourTrendData(deviceNo, channelNo, startTime, endTime, startMeter, endMeter);
        } else if ("month".equalsIgnoreCase(trendType)) {
            return getDailyTrendData(deviceNo, channelNo, startTime, endTime, startMeter, endMeter);
        } else {
            throw new UnsupportedOperationException("不支持的统计类型: " + trendType);
        }
    }

    private TemperatureTrendResponse getMinuteTrendData(String deviceNo, Integer channelNo,
                                                        String startTime, String endTime,
                                                        Integer startMeter, Integer endMeter) {
        long startTimeMillis = System.currentTimeMillis();
        long dbQueryStartTime = 0L;
        long dataProcessStartTime = 0L;
        long trendBuildStartTime = 0L;

        // 设置默认米标范围
        if (startMeter == null) startMeter = 1;
        if (endMeter == null) endMeter = 100;

        // 1. 从分钟统计表中查询指定时间段的数据
        dbQueryStartTime = System.currentTimeMillis();
        List<PjStatsTemperatureMinute> minuteStatsList = pjStatsTemperatureMinuteMapper
                .selectByDeviceChannelAndTimeRange(deviceNo, channelNo, startTime, endTime);
        long dbQueryTime = System.currentTimeMillis() - dbQueryStartTime;

        // 处理数据，将字符串转换为Map
        dataProcessStartTime = System.currentTimeMillis();
        PjStatsTemperatureMinute.processMinuteStatsList(minuteStatsList);
        long dataProcessTime = System.currentTimeMillis() - dataProcessStartTime;

        if (minuteStatsList.isEmpty()) {
            long totalTime = System.currentTimeMillis() - startTimeMillis;
            log.info("getMinuteTrendData - 无数据返回, 总耗时: {}ms (数据库查询: {}ms, 数据处理: {}ms)",
                    totalTime, dbQueryTime, dataProcessTime);
            return new TemperatureTrendResponse(deviceNo, channelNo, new ArrayList<>());
        }

        // 2. 收集所有时间标签
        trendBuildStartTime = System.currentTimeMillis();
        List<String> allTimeLabels = new ArrayList<>();
        for (PjStatsTemperatureMinute minuteStat : minuteStatsList) {
            String timeLabel = formatMinuteTime(minuteStat.getStatTime());
            allTimeLabels.add(timeLabel);
        }

        // 3. 创建响应对象
        TemperatureTrendResponse response = new TemperatureTrendResponse(deviceNo, channelNo, allTimeLabels);

        // 【修改点1】获取通道的实际起始米标（从第一条有效数据中获取）
        Integer channelStartMeter = null;
        for (PjStatsTemperatureMinute stat : minuteStatsList) {
            if (stat.getStartMeter() != null) {
                channelStartMeter = stat.getStartMeter().intValue();
                break;
            }
        }

        // 如果没有找到起始米标，使用默认值1
        if (channelStartMeter == null) {
            channelStartMeter = 1;
            log.warn("未找到通道起始米标，使用默认值: {}", channelStartMeter);
        }

        log.info("通道起始米标: {}, 查询米标范围: {}-{}", channelStartMeter, startMeter, endMeter);

        // 【修改点2】计算数组索引范围
        int arrayStartIndex = Math.max(0, startMeter - channelStartMeter);
        int arrayEndIndex = Math.max(0, endMeter - channelStartMeter);

        log.info("数组索引范围: {}-{} (对应米标: {}-{})",
                arrayStartIndex, arrayEndIndex,
                arrayStartIndex + channelStartMeter,
                arrayEndIndex + channelStartMeter);

        // 4. 确定最大数组长度
        int maxArrayLength = 0;
        for (PjStatsTemperatureMinute stat : minuteStatsList) {
            if (stat.getMaxTemperaturesMap() != null && !stat.getMaxTemperaturesMap().isEmpty()) {
                int maxKey = stat.getMaxTemperaturesMap().keySet().stream()
                        .mapToInt(Integer::intValue)
                        .max()
                        .orElse(0);
                if (maxKey > maxArrayLength) {
                    maxArrayLength = maxKey;
                }
            }
        }

        // 【修改点3】调整结束索引，确保不超过数组边界
        arrayEndIndex = Math.min(arrayEndIndex, maxArrayLength - 1);

        if (arrayStartIndex > arrayEndIndex) {
            long trendBuildTime = System.currentTimeMillis() - trendBuildStartTime;
            long totalTime = System.currentTimeMillis() - startTimeMillis;
            log.warn("getMinuteTrendData - 数组索引范围无效: {}-{}, 最大数组长度: {}, 总耗时: {}ms",
                    arrayStartIndex, arrayEndIndex, maxArrayLength, totalTime);
            return response;
        }

        // 5. 为指定数组索引范围内的每个位置创建温度数据
        long meterDataBuildStartTime = System.currentTimeMillis();
        for (int arrayIndex = arrayStartIndex; arrayIndex <= arrayEndIndex; arrayIndex++) {
            List<BigDecimal> maxValues = new ArrayList<>();

            // 计算对应的实际米标
            int actualMeterMark = channelStartMeter + arrayIndex;

            // 遍历所有分钟数据，直接从Map中获取对应数组索引位置的最高温度值
            for (PjStatsTemperatureMinute minuteStat : minuteStatsList) {
                Map<Integer, BigDecimal> maxTempMap = minuteStat.getMaxTemperaturesMap();

                if (maxTempMap != null && maxTempMap.containsKey(arrayIndex)) {
                    maxValues.add(maxTempMap.get(arrayIndex));
                } else {
                    maxValues.add(BigDecimal.ZERO);
                }
            }

            // 创建米标温度数据并添加到响应中
            MeterTemperatureData meterData = new MeterTemperatureData(
                    actualMeterMark, "max", maxValues  // 使用实际米标值
            );
            response.getMeterData().add(meterData);
        }
        long meterDataBuildTime = System.currentTimeMillis() - meterDataBuildStartTime;

        long trendBuildTime = System.currentTimeMillis() - trendBuildStartTime;
        long totalTime = System.currentTimeMillis() - startTimeMillis;

        // 记录详细的耗时信息
        log.info("getMinuteTrendData - 完成, 总耗时: {}ms (数据库查询: {}ms, 数据处理: {}ms, 趋势构建: {}ms [其中米标数据构建: {}ms]), " +
                        "数据量: {}条记录, 通道起始米标: {}, 数组索引范围: {}-{}, 实际米标范围: {}-{}, 输出米标数: {}",
                totalTime, dbQueryTime, dataProcessTime, trendBuildTime, meterDataBuildTime,
                minuteStatsList.size(), channelStartMeter, arrayStartIndex, arrayEndIndex,
                channelStartMeter + arrayStartIndex, channelStartMeter + arrayEndIndex,
                response.getMeterData().size());

        return response;
    }

    @Override
    public void statsMinute() {
        statisticLog.info("=== 开始执行分钟统计分析 ===");
        long startTime = System.currentTimeMillis();
        // 修改1：明确使用前一分钟的时间进行统计
        LocalDateTime statTime = LocalDateTime.now().minusMinutes(1).withSecond(0).withNano(0);
        statisticLog.info("统计时间（前一分钟）: {}", statTime);

        int totalSuccessCount = 0;
        int totalFailCount = 0;

        try {
            List<DeviceChannel> deviceChannels = pjRealtimeTemperatureDataMapper.selectDistinctDeviceChannels();
            statisticLog.info("获取到 {} 个设备通道组合", deviceChannels.size());

            for (DeviceChannel dc : deviceChannels) {
                boolean success = statsMinuteForDeviceChannel(dc.getDeviceNo(), dc.getChannelNo(), statTime);
                if (success) {
                    totalSuccessCount++;
                } else {
                    totalFailCount++;
                }
            }

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            statisticLog.info("=== 分钟统计分析完成 ===");
            statisticLog.info("统计汇总:");
            statisticLog.info("- 总处理设备通道: {} 个", totalSuccessCount + totalFailCount);
            statisticLog.info("- 成功处理: {} 个", totalSuccessCount);
            statisticLog.info("- 处理失败: {} 个", totalFailCount);
            statisticLog.info("- 成功率: {}%", (totalSuccessCount + totalFailCount) > 0 ?
                    String.format("%.2f", (totalSuccessCount * 100.0 / (totalSuccessCount + totalFailCount))) : "0.00");
            statisticLog.info("- 总耗时: {} 毫秒", duration);
            statisticLog.info("统计时间: {}", statTime);

        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            statisticLog.error("=== 分钟统计分析失败 ===");
            statisticLog.error("错误信息: {}", e.getMessage());
            statisticLog.error("统计时间: {}", statTime);
            statisticLog.error("已成功处理: {} 个设备通道", totalSuccessCount);
            statisticLog.error("处理失败: {} 个设备通道", totalFailCount);
            statisticLog.error("总耗时: {} 毫秒", duration);
            statisticLog.error("异常堆栈:", e);

            log.error("分钟统计分析执行失败", e);
        }
    }

    @Override
    public void statsHour() {
        statisticLog.info("=== 开始执行小时统计分析 ===");
        long startTime = System.currentTimeMillis();
        LocalDateTime statTime = LocalDateTime.now().minusHours(1).withMinute(0).withSecond(0).withNano(0);
        statisticLog.info("统计时间（前一小时）: {}", statTime);

        int totalSuccessCount = 0;
        int totalFailCount = 0;

        try {
            List<DeviceChannel> deviceChannels = pjRealtimeTemperatureDataMapper.selectDistinctDeviceChannels();
            statisticLog.info("获取到 {} 个设备通道组合", deviceChannels.size());

            for (DeviceChannel dc : deviceChannels) {
                boolean success = statsHourForDeviceChannel(dc.getDeviceNo(), dc.getChannelNo(), statTime);
                if (success) {
                    totalSuccessCount++;
                } else {
                    totalFailCount++;
                }
            }

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            statisticLog.info("=== 小时统计分析完成 ===");
            statisticLog.info("统计汇总:");
            statisticLog.info("- 总处理设备通道: {} 个", totalSuccessCount + totalFailCount);
            statisticLog.info("- 成功处理: {} 个", totalSuccessCount);
            statisticLog.info("- 处理失败: {} 个", totalFailCount);
            statisticLog.info("- 成功率: {}%", (totalSuccessCount + totalFailCount) > 0 ?
                    String.format("%.2f", (totalSuccessCount * 100.0 / (totalSuccessCount + totalFailCount))) : "0.00");
            statisticLog.info("- 总耗时: {} 毫秒", duration);
            statisticLog.info("统计时间: {}", statTime);

        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            statisticLog.error("=== 小时统计分析失败 ===");
            statisticLog.error("错误信息: {}", e.getMessage());
            statisticLog.error("统计时间: {}", statTime);
            statisticLog.error("已成功处理: {} 个设备通道", totalSuccessCount);
            statisticLog.error("处理失败: {} 个设备通道", totalFailCount);
            statisticLog.error("总耗时: {} 毫秒", duration);
            statisticLog.error("异常堆栈:", e);

            log.error("小时统计分析执行失败", e);
        }
    }

    @Override
    public void statsDaily() {
        statisticLog.info("=== 开始执行天统计分析 ===");
        long startTime = System.currentTimeMillis();
        LocalDate statDate = LocalDate.now().minusDays(1);
        statisticLog.info("统计日期（前一天）: {}", statDate);

        int totalSuccessCount = 0;
        int totalFailCount = 0;

        try {
            List<DeviceChannel> deviceChannels = pjRealtimeTemperatureDataMapper.selectDistinctDeviceChannels();
            statisticLog.info("获取到 {} 个设备通道组合", deviceChannels.size());

            for (DeviceChannel dc : deviceChannels) {
                boolean success = statsDailyForDeviceChannel(dc.getDeviceNo(), dc.getChannelNo(), statDate);
                if (success) {
                    totalSuccessCount++;
                } else {
                    totalFailCount++;
                }
            }

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            statisticLog.info("=== 天统计分析完成 ===");
            statisticLog.info("统计汇总:");
            statisticLog.info("- 总处理设备通道: {} 个", totalSuccessCount + totalFailCount);
            statisticLog.info("- 成功处理: {} 个", totalSuccessCount);
            statisticLog.info("- 处理失败: {} 个", totalFailCount);
            statisticLog.info("- 成功率: {}%", (totalSuccessCount + totalFailCount) > 0 ?
                    String.format("%.2f", (totalSuccessCount * 100.0 / (totalSuccessCount + totalFailCount))) : "0.00");
            statisticLog.info("- 总耗时: {} 毫秒", duration);
            statisticLog.info("统计日期: {}", statDate);

        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            statisticLog.error("=== 天统计分析失败 ===");
            statisticLog.error("错误信息: {}", e.getMessage());
            statisticLog.error("统计日期: {}", statDate);
            statisticLog.error("已成功处理: {} 个设备通道", totalSuccessCount);
            statisticLog.error("处理失败: {} 个设备通道", totalFailCount);
            statisticLog.error("总耗时: {} 毫秒", duration);
            statisticLog.error("异常堆栈:", e);

            log.error("天统计分析执行失败", e);
        }
    }

    /**
     * 格式化时间为分钟格式 (yyyy-MM-dd HH:mm)
     */
    private String formatMinuteTime(Date date) {
        if (date == null) {
            return "";
        }
        LocalDateTime dateTime = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
    }

    private TemperatureTrendResponse getHourTrendData(String deviceNo, Integer channelNo,
                                                      String startTime, String endTime,
                                                      Integer startMeter, Integer endMeter) {
        long startTimeMillis = System.currentTimeMillis();
        long dbQueryStartTime = 0L;
        long dataProcessStartTime = 0L;
        long trendBuildStartTime = 0L;

        // 设置默认米标范围
        if (startMeter == null) startMeter = 1;
        if (endMeter == null) endMeter = 100;

        // 1. 从小时统计表中查询指定时间段的数据
        dbQueryStartTime = System.currentTimeMillis();
        List<PjStatsTemperatureHour> hourStatsList = pjStatsTemperatureHourMapper
                .selectByDeviceChannelAndTimeRange(deviceNo, channelNo, startTime, endTime);
        long dbQueryTime = System.currentTimeMillis() - dbQueryStartTime;

        // 处理数据，将字符串转换为Map
        dataProcessStartTime = System.currentTimeMillis();
        processHourStatsList(hourStatsList);
        long dataProcessTime = System.currentTimeMillis() - dataProcessStartTime;

        if (hourStatsList.isEmpty()) {
            long totalTime = System.currentTimeMillis() - startTimeMillis;
            log.info("getHourTrendData - 无数据返回, 总耗时: {}ms (数据库查询: {}ms, 数据处理: {}ms)",
                    totalTime, dbQueryTime, dataProcessTime);
            return new TemperatureTrendResponse(deviceNo, channelNo, new ArrayList<>());
        }

        // 2. 收集所有时间标签
        trendBuildStartTime = System.currentTimeMillis();
        List<String> allTimeLabels = new ArrayList<>();
        for (PjStatsTemperatureHour hourStat : hourStatsList) {
            String timeLabel = formatHourTime(hourStat.getStatTime());
            allTimeLabels.add(timeLabel);
        }

        // 3. 创建响应对象
        TemperatureTrendResponse response = new TemperatureTrendResponse(deviceNo, channelNo, allTimeLabels);

        // 【修改点1】获取通道的实际起始米标
        Integer channelStartMeter = null;
        for (PjStatsTemperatureHour stat : hourStatsList) {
            if (stat.getStartMeter() != null) {
                channelStartMeter = stat.getStartMeter().intValue();
                break;
            }
        }

        if (channelStartMeter == null) {
            channelStartMeter = 1;
            log.warn("未找到通道起始米标，使用默认值: {}", channelStartMeter);
        }

        log.info("通道起始米标: {}, 查询米标范围: {}-{}", channelStartMeter, startMeter, endMeter);

        // 【修改点2】计算数组索引范围
        int arrayStartIndex = Math.max(0, startMeter - channelStartMeter);
        int arrayEndIndex = Math.max(0, endMeter - channelStartMeter);

        // 4. 确定最大数组长度
        int maxArrayLength = 0;
        for (PjStatsTemperatureHour stat : hourStatsList) {
            if (stat.getMaxTemperaturesMap() != null && !stat.getMaxTemperaturesMap().isEmpty()) {
                int maxKey = stat.getMaxTemperaturesMap().keySet().stream()
                        .mapToInt(Integer::intValue)
                        .max()
                        .orElse(0);
                if (maxKey > maxArrayLength) {
                    maxArrayLength = maxKey;
                }
            }
        }

        // 【修改点3】调整结束索引，确保不超过数组边界
        arrayEndIndex = Math.min(arrayEndIndex, maxArrayLength - 1);

        if (arrayStartIndex > arrayEndIndex) {
            long trendBuildTime = System.currentTimeMillis() - trendBuildStartTime;
            long totalTime = System.currentTimeMillis() - startTimeMillis;
            log.warn("getHourTrendData - 数组索引范围无效: {}-{}, 最大数组长度: {}, 总耗时: {}ms",
                    arrayStartIndex, arrayEndIndex, maxArrayLength, totalTime);
            return response;
        }

        // 5. 为指定数组索引范围内的每个位置创建温度数据
        long meterDataBuildStartTime = System.currentTimeMillis();
        for (int arrayIndex = arrayStartIndex; arrayIndex <= arrayEndIndex; arrayIndex++) {
            List<BigDecimal> maxValues = new ArrayList<>();

            // 计算对应的实际米标
            int actualMeterMark = channelStartMeter + arrayIndex;

            // 遍历所有小时数据，直接从Map中获取对应数组索引位置的最高温度值
            for (PjStatsTemperatureHour hourStat : hourStatsList) {
                Map<Integer, BigDecimal> maxTempMap = hourStat.getMaxTemperaturesMap();

                if (maxTempMap != null && maxTempMap.containsKey(arrayIndex)) {
                    maxValues.add(maxTempMap.get(arrayIndex));
                } else {
                    maxValues.add(BigDecimal.ZERO);
                }
            }

            // 创建米标温度数据并添加到响应中
            MeterTemperatureData meterData = new MeterTemperatureData(
                    actualMeterMark, "max", maxValues
            );
            response.getMeterData().add(meterData);
        }
        long meterDataBuildTime = System.currentTimeMillis() - meterDataBuildStartTime;

        long trendBuildTime = System.currentTimeMillis() - trendBuildStartTime;
        long totalTime = System.currentTimeMillis() - startTimeMillis;

        log.info("getHourTrendData - 完成, 总耗时: {}ms (数据库查询: {}ms, 数据处理: {}ms, 趋势构建: {}ms [其中米标数据构建: {}ms]), " +
                        "数据量: {}条记录, 通道起始米标: {}, 数组索引范围: {}-{}, 实际米标范围: {}-{}, 输出米标数: {}",
                totalTime, dbQueryTime, dataProcessTime, trendBuildTime, meterDataBuildTime,
                hourStatsList.size(), channelStartMeter, arrayStartIndex, arrayEndIndex,
                channelStartMeter + arrayStartIndex, channelStartMeter + arrayEndIndex,
                response.getMeterData().size());

        return response;
    }

    private TemperatureTrendResponse getDailyTrendData(String deviceNo, Integer channelNo,
                                                       String startTime, String endTime,
                                                       Integer startMeter, Integer endMeter) {
        long startTimeMillis = System.currentTimeMillis();
        long dbQueryStartTime = 0L;
        long dataProcessStartTime = 0L;
        long trendBuildStartTime = 0L;

        // 设置默认米标范围
        if (startMeter == null) startMeter = 1;
        if (endMeter == null) endMeter = 100;

        // 1. 从天统计表中查询指定时间段的数据
        dbQueryStartTime = System.currentTimeMillis();
        List<PjStatsTemperatureDaily> dailyStatsList = pjStatsTemperatureDailyMapper
                .selectByDeviceChannelAndTimeRange(deviceNo, channelNo, startTime, endTime);
        long dbQueryTime = System.currentTimeMillis() - dbQueryStartTime;

        // 处理数据，将字符串转换为Map
        dataProcessStartTime = System.currentTimeMillis();
        processDailyStatsList(dailyStatsList);
        long dataProcessTime = System.currentTimeMillis() - dataProcessStartTime;

        if (dailyStatsList.isEmpty()) {
            long totalTime = System.currentTimeMillis() - startTimeMillis;
            log.info("getDailyTrendData - 无数据返回, 总耗时: {}ms (数据库查询: {}ms, 数据处理: {}ms)",
                    totalTime, dbQueryTime, dataProcessTime);
            return new TemperatureTrendResponse(deviceNo, channelNo, new ArrayList<>());
        }

        // 2. 收集所有时间标签
        trendBuildStartTime = System.currentTimeMillis();
        List<String> allTimeLabels = new ArrayList<>();
        for (PjStatsTemperatureDaily dailyStat : dailyStatsList) {
            String timeLabel = formatDailyTime(dailyStat.getStatDate());
            allTimeLabels.add(timeLabel);
        }

        // 3. 创建响应对象
        TemperatureTrendResponse response = new TemperatureTrendResponse(deviceNo, channelNo, allTimeLabels);

        // 【修改点1】获取通道的实际起始米标
        Integer channelStartMeter = null;
        for (PjStatsTemperatureDaily stat : dailyStatsList) {
            if (stat.getStartMeter() != null) {
                channelStartMeter = stat.getStartMeter().intValue();
                break;
            }
        }

        if (channelStartMeter == null) {
            channelStartMeter = 1;
            log.warn("未找到通道起始米标，使用默认值: {}", channelStartMeter);
        }

        log.info("通道起始米标: {}, 查询米标范围: {}-{}", channelStartMeter, startMeter, endMeter);

        // 【修改点2】计算数组索引范围
        int arrayStartIndex = Math.max(0, startMeter - channelStartMeter);
        int arrayEndIndex = Math.max(0, endMeter - channelStartMeter);

        // 4. 确定最大数组长度
        int maxArrayLength = 0;
        for (PjStatsTemperatureDaily stat : dailyStatsList) {
            if (stat.getMaxTemperaturesMap() != null && !stat.getMaxTemperaturesMap().isEmpty()) {
                int maxKey = stat.getMaxTemperaturesMap().keySet().stream()
                        .mapToInt(Integer::intValue)
                        .max()
                        .orElse(0);
                if (maxKey > maxArrayLength) {
                    maxArrayLength = maxKey;
                }
            }
        }

        // 【修改点3】调整结束索引，确保不超过数组边界
        arrayEndIndex = Math.min(arrayEndIndex, maxArrayLength - 1);

        if (arrayStartIndex > arrayEndIndex) {
            long trendBuildTime = System.currentTimeMillis() - trendBuildStartTime;
            long totalTime = System.currentTimeMillis() - startTimeMillis;
            log.warn("getDailyTrendData - 数组索引范围无效: {}-{}, 最大数组长度: {}, 总耗时: {}ms",
                    arrayStartIndex, arrayEndIndex, maxArrayLength, totalTime);
            return response;
        }

        // 5. 为指定数组索引范围内的每个位置创建温度数据
        long meterDataBuildStartTime = System.currentTimeMillis();
        for (int arrayIndex = arrayStartIndex; arrayIndex <= arrayEndIndex; arrayIndex++) {
            List<BigDecimal> maxValues = new ArrayList<>();

            // 计算对应的实际米标
            int actualMeterMark = channelStartMeter + arrayIndex;

            // 遍历所有天数据，直接从Map中获取对应数组索引位置的最高温度值
            for (PjStatsTemperatureDaily dailyStat : dailyStatsList) {
                Map<Integer, BigDecimal> maxTempMap = dailyStat.getMaxTemperaturesMap();

                if (maxTempMap != null && maxTempMap.containsKey(arrayIndex)) {
                    maxValues.add(maxTempMap.get(arrayIndex));
                } else {
                    maxValues.add(BigDecimal.ZERO);
                }
            }

            // 创建米标温度数据并添加到响应中
            MeterTemperatureData meterData = new MeterTemperatureData(
                    actualMeterMark, "max", maxValues
            );
            response.getMeterData().add(meterData);
        }
        long meterDataBuildTime = System.currentTimeMillis() - meterDataBuildStartTime;

        long trendBuildTime = System.currentTimeMillis() - trendBuildStartTime;
        long totalTime = System.currentTimeMillis() - startTimeMillis;

        log.info("getDailyTrendData - 完成, 总耗时: {}ms (数据库查询: {}ms, 数据处理: {}ms, 趋势构建: {}ms [其中米标数据构建: {}ms]), " +
                        "数据量: {}条记录, 通道起始米标: {}, 数组索引范围: {}-{}, 实际米标范围: {}-{}, 输出米标数: {}",
                totalTime, dbQueryTime, dataProcessTime, trendBuildTime, meterDataBuildTime,
                dailyStatsList.size(), channelStartMeter, arrayStartIndex, arrayEndIndex,
                channelStartMeter + arrayStartIndex, channelStartMeter + arrayEndIndex,
                response.getMeterData().size());

        return response;
    }

    private boolean statsMinuteForDeviceChannel(String deviceNo, Integer channelNo, LocalDateTime statTime) {
        try {
            // 检查是否已统计过
            if (pjStatsTemperatureMinuteMapper.selectCountByDeviceChannelAndTime(deviceNo, channelNo, statTime) > 0) {
                statisticLog.debug("分钟统计已存在 - 设备: {}, 通道: {}, 时间: {}", deviceNo, channelNo, statTime);
                return true;
            }

            // 获取该分钟的实时数据
            List<PjRealtimeTemperatureData> minuteData = pjRealtimeTemperatureDataMapper.selectMinuteRealtimeData(
                    deviceNo, channelNo, statTime.format(MINUTE_FORMATTER));

            if (minuteData.isEmpty()) {
                statisticLog.debug("无实时数据可统计 - 设备: {}, 通道: {}, 时间: {}", deviceNo, channelNo, statTime);
                return false;
            }

            // 计算分钟统计
            PjStatsTemperatureMinute stats = calculateMinuteStats(deviceNo, channelNo, statTime, minuteData);

            // 插入分钟统计
            pjStatsTemperatureMinuteMapper.insertPjStatsTemperatureMinute(stats);

            statisticLog.debug("完成分钟统计 - 设备: {}, 通道: {}, 时间: {}, 样本数: {}",
                    deviceNo, channelNo, statTime, minuteData.size());
            return true;

        } catch (Exception e) {
            statisticLog.error("分钟统计处理失败 - 设备: {}, 通道: {}, 时间: {}, 错误: {}",
                    deviceNo, channelNo, statTime, e.getMessage());
            return false;
        }
    }

    private boolean statsHourForDeviceChannel(String deviceNo, Integer channelNo, LocalDateTime statTime) {
        try {
            // 检查是否已统计过
            if (pjStatsTemperatureHourMapper.selectCountByDeviceChannelAndTime(deviceNo, channelNo, statTime) > 0) {
                statisticLog.debug("小时统计已存在 - 设备: {}, 通道: {}, 时间: {}", deviceNo, channelNo, statTime);
                return true;
            }

            // 获取该小时的所有分钟统计数据
            List<PjStatsTemperatureMinute> hourData = pjStatsTemperatureMinuteMapper.selectByDeviceChannelAndHour(
                    deviceNo, channelNo, statTime);

            if (hourData.isEmpty()) {
                statisticLog.debug("无分钟数据可统计 - 设备: {}, 通道: {}, 时间: {}", deviceNo, channelNo, statTime);
                return false;
            }

            // 计算小时统计
            PjStatsTemperatureHour stats = calculateHourStats(deviceNo, channelNo, statTime, hourData);

            // 插入小时统计
            pjStatsTemperatureHourMapper.insertPjStatsTemperatureHour(stats);

            statisticLog.debug("完成小时统计 - 设备: {}, 通道: {}, 时间: {}, 分钟数: {}",
                    deviceNo, channelNo, statTime, hourData.size());
            return true;

        } catch (Exception e) {
            statisticLog.error("小时统计处理失败 - 设备: {}, 通道: {}, 时间: {}, 错误: {}",
                    deviceNo, channelNo, statTime, e.getMessage());
            return false;
        }
    }

    private boolean statsDailyForDeviceChannel(String deviceNo, Integer channelNo, LocalDate statDate) {
        try {
            // 检查是否已统计过
            if (pjStatsTemperatureDailyMapper.selectCountByDeviceChannelAndDate(deviceNo, channelNo, statDate) > 0) {
                statisticLog.debug("天统计已存在 - 设备: {}, 通道: {}, 日期: {}", deviceNo, channelNo, statDate);
                return true;
            }

            // 获取该天的所有小时统计数据
            List<PjStatsTemperatureHour> dailyData = pjStatsTemperatureHourMapper.selectByDeviceChannelAndDate(
                    deviceNo, channelNo, statDate.toString());

            if (dailyData.isEmpty()) {
                statisticLog.debug("无小时数据可统计 - 设备: {}, 通道: {}, 日期: {}", deviceNo, channelNo, statDate);
                return false;
            }

            // 计算天统计
            PjStatsTemperatureDaily stats = calculateDailyStats(deviceNo, channelNo, statDate, dailyData);

            // 插入天统计
            pjStatsTemperatureDailyMapper.insertPjStatsTemperatureDaily(stats);

            statisticLog.debug("完成天统计 - 设备: {}, 通道: {}, 日期: {}, 小时数: {}",
                    deviceNo, channelNo, statDate, dailyData.size());
            return true;

        } catch (Exception e) {
            statisticLog.error("天统计处理失败 - 设备: {}, 通道: {}, 日期: {}, 错误: {}",
                    deviceNo, channelNo, statDate, e.getMessage());
            return false;
        }
    }

    private PjStatsTemperatureMinute calculateMinuteStats(String deviceNo, Integer channelNo, LocalDateTime statTime,
                                                          List<PjRealtimeTemperatureData> minuteData) {
        // 确定最大数组长度（取所有记录中的最大长度）
        int maxLength = minuteData.stream()
                .mapToInt(data -> Math.max(
                        parseTemperatureArray(data.getMaxTemperatures()).size(),
                        parseTemperatureArray(data.getMinTemperatures()).size()
                ))
                .max()
                .orElse(0);

        // 获取米标范围（从第一条有效数据中获取）
        Double startMeter = null;
        Double endMeter = null;
        for (PjRealtimeTemperatureData data : minuteData) {
            if (data.getStartMeter() != null && data.getEndMeter() != null) {
                startMeter = data.getStartMeter();
                endMeter = data.getEndMeter();
                break;
            }
        }

        if (maxLength == 0) {
            statisticLog.warn("无有效数据可统计 - 设备: {}, 通道: {}, 时间: {}", deviceNo, channelNo, statTime);
            return createEmptyMinuteStats(deviceNo, channelNo, statTime);
        }


        // 初始化统计数组
        List<BigDecimal> maxTemps = new ArrayList<>(maxLength);  // 高温数组：取最大值
        List<BigDecimal> minTemps = new ArrayList<>(maxLength);  // 低温数组：取最小值
        List<BigDecimal> sumTemps = new ArrayList<>(maxLength);  // 用于计算平均值：存储温度总和
        int[] countTemps = new int[maxLength];                  // 每个位置的有效数据计数

        // 初始化数组
        for (int i = 0; i < maxLength; i++) {
            maxTemps.add(null);
            minTemps.add(null);
            sumTemps.add(BigDecimal.ZERO);
            countTemps[i] = 0;
        }

        // 遍历每分钟的所有数据记录（通常12条）
        for (PjRealtimeTemperatureData data : minuteData) {
            List<BigDecimal> dataMaxTemps = parseTemperatureArray(data.getMaxTemperatures());
            List<BigDecimal> dataMinTemps = parseTemperatureArray(data.getMinTemperatures());

            // 处理高温数组：取每个米标位置的最大值
            for (int i = 0; i < dataMaxTemps.size() && i < maxLength; i++) {
                BigDecimal currentMax = dataMaxTemps.get(i);
                if (currentMax != null) {
                    // 更新最大值
                    if (maxTemps.get(i) == null || currentMax.compareTo(maxTemps.get(i)) > 0) {
                        maxTemps.set(i, currentMax);
                    }
                }
            }

            // 处理低温数组：取每个米标位置的最小值
            for (int i = 0; i < dataMinTemps.size() && i < maxLength; i++) {
                BigDecimal currentMin = dataMinTemps.get(i);
                if (currentMin != null) {
                    // 更新最小值
                    if (minTemps.get(i) == null || currentMin.compareTo(minTemps.get(i)) < 0) {
                        minTemps.set(i, currentMin);
                    }
                }
            }

            // 计算平均值：累加每个米标位置的温度值
            for (int i = 0; i < Math.min(dataMaxTemps.size(), dataMinTemps.size()) && i < maxLength; i++) {
                BigDecimal currentMax = dataMaxTemps.get(i);
                BigDecimal currentMin = dataMinTemps.get(i);

                if (currentMax != null && currentMin != null) {
                    // 计算当前记录的平均温度
                    BigDecimal currentAvg = currentMax.add(currentMin).divide(new BigDecimal("2"), 2, RoundingMode.HALF_UP);
                    // 累加到总和
                    sumTemps.set(i, sumTemps.get(i).add(currentAvg));
                    countTemps[i]++;
                }
            }
        }

        // 计算平均温度数组
        List<BigDecimal> avgTemps = new ArrayList<>(maxLength);
        for (int i = 0; i < maxLength; i++) {
            if (countTemps[i] > 0) {
                // 计算平均值：总和 ÷ 计数
                BigDecimal avg = sumTemps.get(i).divide(new BigDecimal(countTemps[i]), 2, RoundingMode.HALF_UP);
                avgTemps.add(avg);
            } else {
                // 没有有效数据的位置设为0
                avgTemps.add(BigDecimal.ZERO);
            }
        }

        // 处理没有数据的位置
        for (int i = 0; i < maxLength; i++) {
            if (maxTemps.get(i) == null) {
                maxTemps.set(i, BigDecimal.ZERO);
            }
            if (minTemps.get(i) == null) {
                minTemps.set(i, BigDecimal.ZERO);
            }
        }

        PjStatsTemperatureMinute stats = new PjStatsTemperatureMinute();
        stats.setDeviceNo(deviceNo);
        stats.setChannelNo(channelNo);
        stats.setStatTime(Date.from(statTime.atZone(ZoneId.systemDefault()).toInstant()));
        stats.setMaxTemperatures(JSON.toJSONString(maxTemps));
        stats.setMinTemperatures(JSON.toJSONString(minTemps));
        stats.setAvgTemperatures(JSON.toJSONString(avgTemps));
        stats.setSampleCount(minuteData.size());

        // 新增：设置米标范围
        stats.setStartMeter(startMeter);
        stats.setEndMeter(endMeter);

        return stats;
    }

    private PjStatsTemperatureHour calculateHourStats(String deviceNo, Integer channelNo, LocalDateTime statTime,
                                                      List<PjStatsTemperatureMinute> hourData) {
        // 确定最大数组长度
        int maxLength = hourData.stream()
                .mapToInt(stats -> {
                    try {
                        JSONArray maxArray = JSON.parseArray(stats.getMaxTemperatures());
                        return maxArray.size();
                    } catch (Exception e) {
                        return 0;
                    }
                })
                .max()
                .orElse(0);

        // 获取米标范围（从第一条有效的分钟统计数据中获取）
        Double startMeter = null;
        Double endMeter = null;
        for (PjStatsTemperatureMinute minuteStats : hourData) {
            if (minuteStats.getStartMeter() != null && minuteStats.getEndMeter() != null) {
                startMeter = minuteStats.getStartMeter();
                endMeter = minuteStats.getEndMeter();
                break;
            }
        }

        if (maxLength == 0) {
            statisticLog.warn("无有效分钟数据可统计 - 设备: {}, 通道: {}, 时间: {}", deviceNo, channelNo, statTime);
            return createEmptyHourStats(deviceNo, channelNo, statTime);
        }

        // 初始化统计数组
        List<BigDecimal> maxTemps = new ArrayList<>(maxLength);  // 高温数组：取最大值
        List<BigDecimal> minTemps = new ArrayList<>(maxLength);  // 低温数组：取最小值
        List<BigDecimal> sumTemps = new ArrayList<>(maxLength);  // 用于计算平均值：存储温度总和
        int[] countTemps = new int[maxLength];                  // 每个位置的有效数据计数

        // 初始化数组
        for (int i = 0; i < maxLength; i++) {
            maxTemps.add(null);
            minTemps.add(null);
            sumTemps.add(BigDecimal.ZERO);
            countTemps[i] = 0;
        }

        int totalSampleCount = 0;

        for (PjStatsTemperatureMinute minuteStats : hourData) {
            try {
                List<BigDecimal> minuteMaxTemps = JSON.parseArray(minuteStats.getMaxTemperatures(), BigDecimal.class);
                List<BigDecimal> minuteMinTemps = JSON.parseArray(minuteStats.getMinTemperatures(), BigDecimal.class);
                List<BigDecimal> minuteAvgTemps = JSON.parseArray(minuteStats.getAvgTemperatures(), BigDecimal.class);

                // 处理高温数组：取最大值
                for (int i = 0; i < minuteMaxTemps.size() && i < maxLength; i++) {
                    BigDecimal currentMax = minuteMaxTemps.get(i);
                    if (currentMax != null) {
                        if (maxTemps.get(i) == null || currentMax.compareTo(maxTemps.get(i)) > 0) {
                            maxTemps.set(i, currentMax);
                        }
                    }
                }

                // 处理低温数组：取最小值
                for (int i = 0; i < minuteMinTemps.size() && i < maxLength; i++) {
                    BigDecimal currentMin = minuteMinTemps.get(i);
                    if (currentMin != null) {
                        if (minTemps.get(i) == null || currentMin.compareTo(minTemps.get(i)) < 0) {
                            minTemps.set(i, currentMin);
                        }
                    }
                }

                // 计算平均值：累加平均值
                for (int i = 0; i < minuteAvgTemps.size() && i < maxLength; i++) {
                    BigDecimal currentAvg = minuteAvgTemps.get(i);
                    if (currentAvg != null) {
                        sumTemps.set(i, sumTemps.get(i).add(currentAvg));
                        countTemps[i]++;
                    }
                }

                totalSampleCount += minuteStats.getSampleCount();

            } catch (Exception e) {
                statisticLog.warn("解析分钟统计数据失败 - 设备: {}, 通道: {}, 错误: {}", deviceNo, channelNo, e.getMessage());
            }
        }

        // 计算平均温度数组
        List<BigDecimal> avgTemps = new ArrayList<>(maxLength);
        for (int i = 0; i < maxLength; i++) {
            if (countTemps[i] > 0) {
                BigDecimal avg = sumTemps.get(i).divide(new BigDecimal(countTemps[i]), 2, RoundingMode.HALF_UP);
                avgTemps.add(avg);
            } else {
                avgTemps.add(BigDecimal.ZERO);
            }
        }

        // 处理没有数据的位置
        for (int i = 0; i < maxLength; i++) {
            if (maxTemps.get(i) == null) {
                maxTemps.set(i, BigDecimal.ZERO);
            }
            if (minTemps.get(i) == null) {
                minTemps.set(i, BigDecimal.ZERO);
            }
        }

        PjStatsTemperatureHour stats = new PjStatsTemperatureHour();
        stats.setDeviceNo(deviceNo);
        stats.setChannelNo(channelNo);
        stats.setStatTime(Date.from(statTime.atZone(ZoneId.systemDefault()).toInstant()));
        stats.setMaxTemperatures(JSON.toJSONString(maxTemps));
        stats.setMinTemperatures(JSON.toJSONString(minTemps));
        stats.setAvgTemperatures(JSON.toJSONString(avgTemps));
        stats.setSampleCount(totalSampleCount);

        // 新增：设置米标范围
        stats.setStartMeter(startMeter);
        stats.setEndMeter(endMeter);

        return stats;
    }

    private PjStatsTemperatureDaily calculateDailyStats(String deviceNo, Integer channelNo, LocalDate statDate,
                                                        List<PjStatsTemperatureHour> dailyData) {
        // 确定最大数组长度
        int maxLength = dailyData.stream()
                .mapToInt(stats -> {
                    try {
                        JSONArray maxArray = JSON.parseArray(stats.getMaxTemperatures());
                        return maxArray.size();
                    } catch (Exception e) {
                        return 0;
                    }
                })
                .max()
                .orElse(0);

        // 获取米标范围（从第一条有效的小时统计数据中获取）
        Double startMeter = null;
        Double endMeter = null;
        for (PjStatsTemperatureHour hourStats : dailyData) {
            if (hourStats.getStartMeter() != null && hourStats.getEndMeter() != null) {
                startMeter = hourStats.getStartMeter();
                endMeter = hourStats.getEndMeter();
                break;
            }
        }

        if (maxLength == 0) {
            statisticLog.warn("无有效小时数据可统计 - 设备: {}, 通道: {}, 日期: {}", deviceNo, channelNo, statDate);
            return createEmptyDailyStats(deviceNo, channelNo, statDate);
        }

        // 初始化统计数组
        List<BigDecimal> maxTemps = new ArrayList<>(maxLength);  // 高温数组：取最大值
        List<BigDecimal> minTemps = new ArrayList<>(maxLength);  // 低温数组：取最小值
        List<BigDecimal> sumTemps = new ArrayList<>(maxLength);  // 用于计算平均值：存储温度总和
        int[] countTemps = new int[maxLength];                  // 每个位置的有效数据计数

        // 初始化数组
        for (int i = 0; i < maxLength; i++) {
            maxTemps.add(null);
            minTemps.add(null);
            sumTemps.add(BigDecimal.ZERO);
            countTemps[i] = 0;
        }

        int totalSampleCount = 0;

        for (PjStatsTemperatureHour hourStats : dailyData) {
            try {
                List<BigDecimal> hourMaxTemps = JSON.parseArray(hourStats.getMaxTemperatures(), BigDecimal.class);
                List<BigDecimal> hourMinTemps = JSON.parseArray(hourStats.getMinTemperatures(), BigDecimal.class);
                List<BigDecimal> hourAvgTemps = JSON.parseArray(hourStats.getAvgTemperatures(), BigDecimal.class);

                // 处理高温数组：取最大值
                for (int i = 0; i < hourMaxTemps.size() && i < maxLength; i++) {
                    BigDecimal currentMax = hourMaxTemps.get(i);
                    if (currentMax != null) {
                        if (maxTemps.get(i) == null || currentMax.compareTo(maxTemps.get(i)) > 0) {
                            maxTemps.set(i, currentMax);
                        }
                    }
                }

                // 处理低温数组：取最小值
                for (int i = 0; i < hourMinTemps.size() && i < maxLength; i++) {
                    BigDecimal currentMin = hourMinTemps.get(i);
                    if (currentMin != null) {
                        if (minTemps.get(i) == null || currentMin.compareTo(minTemps.get(i)) < 0) {
                            minTemps.set(i, currentMin);
                        }
                    }
                }

                // 计算平均值：累加平均值
                for (int i = 0; i < hourAvgTemps.size() && i < maxLength; i++) {
                    BigDecimal currentAvg = hourAvgTemps.get(i);
                    if (currentAvg != null) {
                        sumTemps.set(i, sumTemps.get(i).add(currentAvg));
                        countTemps[i]++;
                    }
                }

                totalSampleCount += hourStats.getSampleCount();

            } catch (Exception e) {
                statisticLog.warn("解析小时统计数据失败 - 设备: {}, 通道: {}, 错误: {}", deviceNo, channelNo, e.getMessage());
            }
        }

        // 计算平均温度数组
        List<BigDecimal> avgTemps = new ArrayList<>(maxLength);
        for (int i = 0; i < maxLength; i++) {
            if (countTemps[i] > 0) {
                BigDecimal avg = sumTemps.get(i).divide(new BigDecimal(countTemps[i]), 2, RoundingMode.HALF_UP);
                avgTemps.add(avg);
            } else {
                avgTemps.add(BigDecimal.ZERO);
            }
        }

        // 处理没有数据的位置
        for (int i = 0; i < maxLength; i++) {
            if (maxTemps.get(i) == null) {
                maxTemps.set(i, BigDecimal.ZERO);
            }
            if (minTemps.get(i) == null) {
                minTemps.set(i, BigDecimal.ZERO);
            }
        }

        PjStatsTemperatureDaily stats = new PjStatsTemperatureDaily();
        stats.setDeviceNo(deviceNo);
        stats.setChannelNo(channelNo);
        stats.setStatDate(Date.from(statDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        stats.setMaxTemperatures(JSON.toJSONString(maxTemps));
        stats.setMinTemperatures(JSON.toJSONString(minTemps));
        stats.setAvgTemperatures(JSON.toJSONString(avgTemps));
        stats.setSampleCount(totalSampleCount);

        // 新增：设置米标范围
        stats.setStartMeter(startMeter);
        stats.setEndMeter(endMeter);

        return stats;
    }

    private List<BigDecimal> parseTemperatureArray(String jsonStr) {
        if (jsonStr == null || jsonStr.trim().isEmpty() || "null".equalsIgnoreCase(jsonStr.trim())) {
            log.debug("解析温度数组: 输入为null或空");
            return new ArrayList<>();
        }

        try {
            log.debug("开始解析温度数组: {}", jsonStr);
            JSONArray jsonArray = JSON.parseArray(jsonStr);
            List<BigDecimal> result = new ArrayList<>(jsonArray.size());

            for (int i = 0; i < jsonArray.size(); i++) {
                Object value = jsonArray.get(i);
                BigDecimal temp = null;

                if (value instanceof BigDecimal) {
                    temp = (BigDecimal) value;
                } else if (value instanceof Number) {
                    temp = BigDecimal.valueOf(((Number) value).doubleValue());
                } else if (value instanceof String) {
                    String strValue = ((String) value).trim();
                    if (!strValue.isEmpty() && !"null".equalsIgnoreCase(strValue)) {
                        temp = new BigDecimal(strValue);
                    }
                } else if (value != null) {
                    temp = new BigDecimal(value.toString());
                }

                result.add(temp != null ? temp : BigDecimal.ZERO);
            }

            log.debug("解析温度数组完成: {} -> {}", jsonStr, result);
            return result;
        } catch (Exception e) {
            log.warn("解析温度数组失败: {}, 错误: {}", jsonStr, e.getMessage());
            return new ArrayList<>();
        }
    }

    private PjStatsTemperatureMinute createEmptyMinuteStats(String deviceNo, Integer channelNo, LocalDateTime statTime) {
        PjStatsTemperatureMinute stats = new PjStatsTemperatureMinute();
        stats.setDeviceNo(deviceNo);
        stats.setChannelNo(channelNo);
        stats.setStatTime(Date.from(statTime.atZone(ZoneId.systemDefault()).toInstant()));
        stats.setMaxTemperatures("[]");
        stats.setMinTemperatures("[]");
        stats.setAvgTemperatures("[]");
        stats.setSampleCount(0);
        return stats;
    }

    private PjStatsTemperatureHour createEmptyHourStats(String deviceNo, Integer channelNo, LocalDateTime statTime) {
        PjStatsTemperatureHour stats = new PjStatsTemperatureHour();
        stats.setDeviceNo(deviceNo);
        stats.setChannelNo(channelNo);
        stats.setStatTime(Date.from(statTime.atZone(ZoneId.systemDefault()).toInstant()));
        stats.setMaxTemperatures("[]");
        stats.setMinTemperatures("[]");
        stats.setAvgTemperatures("[]");
        stats.setSampleCount(0);
        stats.setStartMeter(null);
        stats.setEndMeter(null);
        return stats;
    }

    private PjStatsTemperatureDaily createEmptyDailyStats(String deviceNo, Integer channelNo, LocalDate statDate) {
        PjStatsTemperatureDaily stats = new PjStatsTemperatureDaily();
        stats.setDeviceNo(deviceNo);
        stats.setChannelNo(channelNo);
        stats.setStatDate(Date.from(statDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        stats.setMaxTemperatures("[]");
        stats.setMinTemperatures("[]");
        stats.setAvgTemperatures("[]");
        stats.setSampleCount(0);
        return stats;
    }

    /**
     * 处理小时统计数据，将JSON字符串转换为Map
     */
    private void processHourStatsList(List<PjStatsTemperatureHour> hourStatsList) {
        for (PjStatsTemperatureHour stat : hourStatsList) {
            if (stat.getMaxTemperatures() != null && !stat.getMaxTemperatures().isEmpty()) {
                try {
                    List<BigDecimal> tempList = JSON.parseArray(stat.getMaxTemperatures(), BigDecimal.class);
                    Map<Integer, BigDecimal> tempMap = new java.util.HashMap<>();
                    for (int i = 0; i < tempList.size(); i++) {
                        if (tempList.get(i) != null) {
                            tempMap.put(i + 1, tempList.get(i));
                        }
                    }
                    stat.setMaxTemperaturesMap(tempMap);
                } catch (Exception e) {
                    log.warn("解析小时统计数据失败: {}", e.getMessage());
                    stat.setMaxTemperaturesMap(new java.util.HashMap<>());
                }
            } else {
                stat.setMaxTemperaturesMap(new java.util.HashMap<>());
            }
        }
    }

    /**
     * 处理天统计数据，将JSON字符串转换为Map
     */
    private void processDailyStatsList(List<PjStatsTemperatureDaily> dailyStatsList) {
        for (PjStatsTemperatureDaily stat : dailyStatsList) {
            if (stat.getMaxTemperatures() != null && !stat.getMaxTemperatures().isEmpty()) {
                try {
                    List<BigDecimal> tempList = JSON.parseArray(stat.getMaxTemperatures(), BigDecimal.class);
                    Map<Integer, BigDecimal> tempMap = new java.util.HashMap<>();
                    for (int i = 0; i < tempList.size(); i++) {
                        if (tempList.get(i) != null) {
                            tempMap.put(i + 1, tempList.get(i));
                        }
                    }
                    stat.setMaxTemperaturesMap(tempMap);
                } catch (Exception e) {
                    log.warn("解析天统计数据失败: {}", e.getMessage());
                    stat.setMaxTemperaturesMap(new java.util.HashMap<>());
                }
            } else {
                stat.setMaxTemperaturesMap(new java.util.HashMap<>());
            }
        }
    }

    /**
     * 格式化时间为小时格式 (yyyy-MM-dd HH:00)
     */
    private String formatHourTime(Date date) {
        if (date == null) {
            return "";
        }
        LocalDateTime dateTime = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:00"));
    }

    /**
     * 格式化时间为天格式 (yyyy-MM-dd)
     */
    private String formatDailyTime(Date date) {
        if (date == null) {
            return "";
        }
        LocalDate localDate = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        return localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }
}